import os
import time
import zipfile

from app.business.model_config import get_model_config
from app.initializer import init_config

# token = 'eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiI3MjAwODM5NCIsInJvbCI6IlJPTEVfUkVHSVNURVIiLCJpc3MiOiJPcGVuWExhYiIsImlhdCI6MTc1MDk0NDM2MiwiY2xpZW50SWQiOiJsa3pkeDU3bnZ5MjJqa3BxOXgydyIsInBob25lIjoiIiwib3BlbklkIjpudWxsLCJ1dWlkIjoiYzMzMzJhZGItYzQ3OS00MzEyLTgzM2YtZjQyYzRlMjgxZGFjIiwiZW1haWwiOiIiLCJleHAiOjE3NTIxNTM5NjJ9.Q6fFd1j2vbeQnjHcjRTSRVhQT2JdheOy_mvcAjTaCF2Lgskw0T6h_AUcdNLkb6EwRObfK1Gn7q77jv9INpwkhw'  # 替换为你的实际token
#创建任务
import requests
def create_task(file_url):
    url='https://mineru.net/api/v4/extract/task'
    token   = get_model_config(model_name="minerU").model_api_key
    header = {
        'Content-Type':'application/json',
        'Authorization': f'Bearer {token}'
    }
    print(header)
    print("开始创建任务"+file_url)
    data = {
        'url':file_url,
        'is_ocr':True,
        'extra_formats' :["docx"]
    }

    res = requests.post(url,headers=header,json=data)
    print(res.status_code)
    print(res.json())
    # print(res.json()["data"]["task_id"])
    return res.json()["data"]["task_id"]
# create_task()
# {'task_id': '52043ed4-978e-475b-9389-2bc7ae92f954'}
def get_task_result( task_id_i):
    token  =get_model_config(model_name="minerU").model_api_key
    task_id = task_id_i
    url = f'https://mineru.net/api/v4/extract/task/{task_id}'
    header = {
        'Content-Type':'application/json',
        'Authorization': f'Bearer {token}'
    }
    print(header)
    res = requests.get(url, headers=header)
    print(res.status_code)
    print(res.json())
    #done 任务处理状态，完成:done，pending: 排队中，running: 正在解析，failed：解析失败，converting：格式转换中
    # print(res.json()["data"]["full_zip_url"])
    return res.json()["data"]
def download_file(url, filename,extract_dir):
    # 拼接完整的保存路径
    file_path = os.path.join(extract_dir, filename)
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with open(file_path, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)
    return  file_path
def extract_zip(zip_path, extract_to):
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(extract_to)

def process_file(file_url):
    task_id = create_task(file_url)
    # task_id = 'ccce9684-d540-4e60-bc59-1db7bfe28410'
    print(f"任务ID: {task_id}")
    max_wait = 600  # 10分钟
    interval = 30
    waited = 0
    while waited < max_wait:
        data = get_task_result(task_id)
        state = data["state"]
        print(f"当前状态: {state}")
        if state == "done":
            zip_url = data["full_zip_url"]
            zip_filename = f"{task_id}_result.zip"
            extract_dir = f"zip/{task_id}_result"
            if not os.path.exists(extract_dir):
                os.makedirs(extract_dir)
            file_zip_url =download_file(zip_url, zip_filename,extract_dir)
            extract_zip(file_zip_url, extract_dir)
            docx_path = os.path.join(extract_dir, "full.docx")
            return docx_path
        elif state == "failed":
            print("任务失败")
            break
        time.sleep(interval)
        waited += interval
    print("超时未完成")
    return None
# get_task_result('85964122-5b06-4344-89c8-24be48b785be')